package com.ljb.haikanglibrary.utils;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

/**
 * Json转化工具类
 * Created by lijianbin on 2017/3/29.
 */

public class JsonKit {
    private JsonKit() {
    }

    /**
     * 对象转json串
     *
     * @param o
     * @return
     */
    public static String toJson(Object o) {
        String json = null;
        if (o != null) {
            json = new Gson().toJson(o);
        }
        return json;
    }

    /**
     * json串转对象
     *
     * @param jsonString
     * @param clazz
     * @return
     */
    public static <T> T toObj(String jsonString, Class<T> clazz) {
        if (jsonString == null || jsonString.trim().length() == 0)
            throw new IllegalArgumentException("需求解析的字符串不能为空");
        return new Gson().fromJson(jsonString, clazz);
    }

    /**
     * json串转list集合
     *
     * @param jsonString
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> toList(String jsonString, Class<T> clazz) {
        List<T> list = new ArrayList<>();

        if (jsonString == null || jsonString.trim().length() == 0)
            throw new IllegalArgumentException("需求解析的字符串不能为空");

        try {
            JSONArray jsonArray = new JSONArray(jsonString);
            for (int i = 0; i < jsonArray.length(); i++) {
                T t = (T) jsonArray.get(i);
                list.add(t);
            }

            L.e("list:" + list.toString());
            return list;

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}
